<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Advertise as AdvertiseModel;
use app\common\model\User;

/**
 * 广告接口
 */
class Adoperate extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test','resetad','fenhong'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    /**
     * 广告价格 与 剩余条数
     * @return [type] [description]
     */
    public function init()
    {
        $price = config('site.advertise_price');
        $time = config('site.advertise_time');

        $advertise_membernum = config('site.advertise_membernum');
        $usernum = User::count();
        $all_user = $advertise_membernum + $usernum;
        $user=$this->auth->getUser();
        $surplus = $user->adnum;
        $ad = new  AdvertiseModel();
        $sum = $ad->where('user_id',$this->auth->id)->sum('totalnum');
        $this->success('返回成功',['price'=>$price,'surplus'=>$surplus,'time'=>$time,'sum'=>$sum+$surplus,'all_user'=>$all_user]);
    }

    /**
     * 我发布的任务列表
     * 'draft','wait','pass','finish','refuse'
     * @param int $page 页数
     * @param string $status 任务状态
     * @return [type] [description]
     */
    public function myadvertise()
    {
        $page = $this->request->request('page',1);
        $status = $this->request->request('status','all');

        if (!in_array($status, ['draft','wait','pass','finish','refuse',''])) {
            $this->error('输入的广告状态不正确！code draft,wait,pass,finish,refuse');
        }

        $advertise = new AdvertiseModel();
        $where = [];
        if ($status!='all') {
            $where['status']=$status;
        }
        $ads=$advertise->where('user_id',$this->auth->id)->where($where)->limit(10)->page($page)->select();
        $this->success('返回成功',['list'=>$ads]);
    }

    /**
     * 发布任务 || 存为草稿
     *
     * @param int $id 编辑广告才会传入
     * @param string $type 广告类型  images || imagestext  || link
     * @param int $totalnum 发布的总次数
     * @param string  $title 标题
     * @param string $images 文图  类型图片广告
     * @param string $content 文图广告  类型图文比传
     * @param string $video 视频广告  类型视频广告比传
     * @param int $totak 广告点击数  
     * @param string $status 广告的状态
     * @return [type] [description]
     */
    public function publish()
    {
        $request = $this->request->request();
        $advertise = new AdvertiseModel();
        $advertise->user_id=$this->auth->id;
        
        switch ($request['type']) {
            case 'link':
                $validete='Advertise.addlink';
                if (strpos($request['content'], 'http://')===false || strpos($request['content'], 'https://')===false) {
                       // $this->success('success');
                }else{
                    $this->error('请按要求填写广告');
                }
                break;
            case 'image':
                $validete='Advertise.addimage';
                break;
            case 'imagetext':
                $validete='Advertise.addimagetext';
                break;
            case 'video':
                $validete='Advertise.addvideo';
                break;
            default:
                $validete='Advertise.addimage';
                break;
        }
        if (!empty($request['id'])) {
            $myad=$advertise->where('user_id',$this->auth->id)->where('status','draft')->where('id',$request['id'])->find();
            if (empty($myad)) {
                $this->error('找不到该广告或广告状态不允许修改');
            }
            $request['status'] = 'draft';
            $result = $advertise->allowField(true)->validate($validete)->save($request,['id'=>$request['id']]);
            $msg='修改成功';
        }else{
        	if (empty($request['totalnum'])) {
        		$this->error('发布的总条数');
        	}
        	$advertise->surplusnum=$request['totalnum'];
            $request['status'] = 'draft';
            $result = $advertise->allowField(true)->validate($validete)->save($request);
            $msg='发布成功';
        }
        
        if(false === $result){
            $this->error($advertise->getError());
        }else{
            // 这里编写扣除广告条数和扣除记录
            db('user')->where('id',$this->auth->id)->setDec('adnum',$request['totalnum']);
        }
        $this->success($msg);
    }

    /**
     * 购买广告条数
     * @param int $num 购买的条数
     * @return [type] [description]
     */
    public function buy()
    {
        $num = $this->request->request('num');
        if ($num <= 0) {
           $this->error('请输入正确的条数');
        }
        $user=$this->auth->getUser();
        $price = config('site.advertise_price');
        $token = $this->auth->getUserToken();

        if ($token->USD < $num) {
            $this->error('余额不足');
        }
        // 这里编写增加广告条数和扣除USD记录
        User::tokenlog('USD',$this->auth->id,0,-$num,'buyad','买广告');
        db('user')->where('id',$this->auth->id)->setInc('adnum',$num/$price);
        $this->success('购买成功');
    }

    /**
     * 随机取出一条广告给会员
     * @return [type] [description]
     */
    public function showadvertise()
    {
        $advertise = new AdvertiseModel();
        $ad=$advertise->where('surplusnum','>',0)->where('status','pass')->orderRaw('rand()')->find();
        $ad_view = config('site.advertise_num');
        $value = $this->auth->getUserExtend('viewad');
        $time = config('site.advertise_time');
        if (empty($ad)) {
            $this->error('暂无广告观看',['tasknum'=>0,'now'=>0,'time'=>0]);
        }
        if ($ad->type == 'link' && !empty($time['link'])) {
            $viewtime = (int)$time['link'];
        }elseif ($ad->type == 'imagetext' && !empty($time['imagetext'])) {
            $viewtime = (int)$time['imagetext'];
        }else{
            $viewtime = 10 ;
        }

        $this->success('返回成功',['info'=>$ad,'tasknum'=>$ad_view,'now'=>$value,'time'=>$viewtime]);
    }

    /**
     * 观看广告提交观看完成
     * @return [type] [description]
     */
    public function finishad()
    {
        $id = $this->request->request('id',0);
        if ($id <= 0) {
            $this->error('ID 错误');
        }
        $ad_view = config('site.advertise_num');
        $advertise = new AdvertiseModel();
        $advertise->where('id',$id)->dec('surplusnum')->update();
        $value = $this->auth->getUserExtend('viewad');
        if ($ad_view == $value) {
            $this->success('您已经完成了今天的任务');
        }
        $this->auth->setUserExtend('viewad',++$value);

        if ($ad_view == $value) {
            //调用矿机控制器挖矿方法
            $rsp = controller('Mineral')->mining();
        }
        $this->success('浏览结束',['ad_view'=>$ad_view,'surplus'=>$ad_view-$value]);
        
    }

    public function fenhong()
    {
        $list = db('user')->where('id','>',0)->select();
        echo json_encode($list);
        foreach ($list as $li) {
            $this->auth->direct($li['id']);
            controller('Mineral')->mining();
        }
        
        
    }
    /**
     * 充值短信条数
     * @return [type] [description]
     */
    public function recharge()
    {
        $id = $this->request->request('id',0);
        $num = $this->request->request('num',0);
        $surplus = db('user')->where('id',$this->auth->id)->value('adnum');

        if ($surplus < $num) {
            $this->error('广告数量不足');
        }

        db('user')->where('id',$this->auth->id)->setDec('adnum',$num);

        $advertise = new AdvertiseModel();
        $advertise->where('id',$id)->inc('surplusnum',$num)->inc('totalnum',$num)->update();
        // echo $advertise->getLastSql();
        $this->success('充值成功');

    }

    public function resetad()
    {
        db('user')->where('id','>',0)->setField('extend',json_encode(array('viewad' => 0,'viewtime'=> strtotime(date('Y-m-d')))));
        db('mineral')->where('id','>',0)->update(['today' => 0,'already'=>0]);
        $this->success('清理成功！');
    }
}
